// {{ AURA-X: 完全重写 - 参考示例项目添加操作按钮和自动填写. Approval: 寸止 }}

console.log('[Augment Auto] Content script loaded');

let currentAction = null;
let userData = null;
let isProcessing = false;
let sidePanel = null;

// 监听来自background的消息
chrome.runtime.onMessage.addListener((request) => {
  if (request.action === 'pageReady') {
    console.log('[Augment Auto] Page ready, action:', request.currentAction);
    currentAction = request.currentAction;

    setTimeout(() => {
      initAutomation();
    }, 1000);
  }
});

// 初始化自动化
async function initAutomation() {
  if (isProcessing) return;
  isProcessing = true;
  
  const url = window.location.href;
  const { currentAction, currentData, flowStep } = await chrome.storage.local.get([
    'currentAction',
    'currentData',
    'flowStep'
  ]);
  
  console.log('[Augment Auto] Init automation:', { url, currentAction, flowStep, currentData });
  
  // {{ AURA-X: Modify - 确保任何页面都能加载按钮. Approval: 寸止 }}
  // 判断当前页面类型
  if (url.includes('/auth/continue') || url.includes('/complete-signup')) {
    // 步骤1: 注册成功页面 - 提取并暂存信息
    console.log('[Augment Auto] Step 1: Extracting account data from auth/continue or complete-signup');
    await handleRegistrationSuccess(currentData);
  } else if (url.includes('/account/subscription')) {
    // 步骤2: Subscription页面 - 获取完整信息并保存
    console.log('[Augment Auto] Step 2: Fetching full account data from subscription');
    await handleSubscriptionPage(currentData);
  } else if (url.includes('/onboard')) {
    // {{ AURA-X: Add - 处理onboard页面，持续监听并点击Skip for now. Approval: 寸止 }}
    // Onboard页面 - 持续监听并点击Skip for now按钮
    console.log('[Augment Auto] Detected onboard page, monitoring for Skip for now button...');
    monitorAndClickSkipForNow();
  } else if (url.includes('auth.augmentcode.com') || url.includes('login.augmentcode.com') || url.includes('/u/login') || url.includes('/u/signup')) {
    // 注册/登录页面
    console.log('[Augment Auto] Detected auth page, handling...');
    await handleAuthPage(currentData);
  } else if (url.includes('billing.augmentcode.com')) {
    // Stripe绑卡页面
    await handleStripeBillingPage(currentData);
  } else if (url.includes('/dashboard')) {
    // Dashboard页面
    await handleAuthPage(currentData);
  } else {
    console.log('[Augment Auto] Unknown page type, still loading buttons');
    // 即使页面类型未知，也要加载按钮
    await handleAuthPage(currentData);
  }
}

// ========== 创建侧边操作面板 ==========

function createSidePanel() {
  // 移除旧面板
  const old = document.getElementById('augment-auto-panel');
  if (old) old.remove();

  sidePanel = document.createElement('div');
  sidePanel.id = 'augment-auto-panel';

  console.log('[Augment Auto] Creating side panel...');
  sidePanel.innerHTML = `
    <style>
      #augment-auto-panel {
        position: fixed;
        top: 50%;
        right: 20px;
        transform: translateY(-50%);
        z-index: 999999;
        display: flex !important;
        flex-direction: column !important;
        gap: 10px;
        background: rgba(0,0,0,0.8);
        backdrop-filter: blur(10px);
        padding: 16px;
        border-radius: 12px;
        box-shadow: 0 4px 24px rgba(0,0,0,0.3);
        min-width: 180px;
        max-width: 220px;
        max-height: 90vh;
        overflow-y: auto;
      }

      /* {{ AURA-X: Modify - 完全复用主页action-card样式. Approval: 寸止 }} */
      #panel-buttons {
        display: flex !important;
        flex-direction: column !important;
        gap: 12px;
      }

      #panel-buttons .action-card {
        width: 100%;
        padding: 12px 16px;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        text-align: center;
        color: #fff;
      }

      #panel-buttons .card-register { background: linear-gradient(135deg, #42c9c2 0%, #5b8cfa 100%); }
      #panel-buttons .card-bind { background: linear-gradient(135deg, #ffb75e 0%, #ed8f03 100%); }
      #panel-buttons .card-all { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
      #panel-buttons .card-verify { background: linear-gradient(135deg, #3d855e 0%, #2e7d32 100%); }
      #panel-buttons .card-delete { background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%); }

      #panel-buttons .action-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 16px rgba(0,0,0,0.15);
      }

      #panel-buttons .card-icon {
        display: none !important;
      }

      #panel-buttons .card-title {
        font-size: 14px;
        font-weight: 600;
        line-height: 1.4;
      }

      #panel-buttons .card-desc {
        display: none !important;
      }

      #panel-title {
        color: white;
        font-size: 16px;
        font-weight: 700;
        margin-bottom: 8px;
        text-align: center;
        padding-bottom: 12px;
        border-bottom: 1px solid rgba(255,255,255,0.2);
      }

      #panel-status {
        color: #42c9c2;
        font-size: 12px;
        text-align: center;
        margin-bottom: 8px;
      }
    </style>
    <div id="panel-title">🎯 自动操作</div>
    <div id="panel-status">等待操作...</div>
    <div id="panel-buttons"></div>
  `;

  // {{ AURA-X: Modify - 确保body存在，否则等待. Approval: 寸止 }}
  if (document.body) {
    document.body.appendChild(sidePanel);
    console.log('[Augment Auto] Side panel added to body');
  } else {
    // body还没准备好，等待DOMContentLoaded
    console.warn('[Augment Auto] document.body not ready, waiting...');
    document.addEventListener('DOMContentLoaded', () => {
      if (document.body && !document.getElementById('augment-auto-panel')) {
        document.body.appendChild(sidePanel);
        console.log('[Augment Auto] Side panel added to body after DOMContentLoaded');
      }
    });
  }
}

// {{ AURA-X: Add - 带卡片样式的addButton函数. Approval: 寸止 }}
function addButton(text, onClick, className = 'card-register') {
  // {{ AURA-X: Modify - 添加多层容错. Approval: 寸止 }}
  let buttonsContainer = document.getElementById('panel-buttons');

  if (!buttonsContainer) {
    console.error('[Augment Auto] Buttons container not found, trying to recreate panel...');
    // 尝试重新创建面板
    const panel = document.getElementById('augment-auto-panel');
    if (panel) panel.remove();
    createSidePanel();

    // 再次尝试获取容器
    buttonsContainer = document.getElementById('panel-buttons');
    if (!buttonsContainer) {
      console.error('[Augment Auto] Still cannot find buttons container after recreating panel!');
      return;
    }
  }

  console.log('[Augment Auto] Adding button:', text);

  const button = document.createElement('button');
  button.className = `action-card ${className}`;

  // 简洁文本，去除emoji
  const cleanText = text.replace(/^[\u{1F300}-\u{1F9FF}]\s*/u, '');

  button.innerHTML = `
    <div class="card-title">${cleanText}</div>
  `;

  button.addEventListener('click', onClick);

  buttonsContainer.appendChild(button);
}

// {{ AURA-X: Modify - 添加主页3个主按钮. Approval: 寸止 }}
function addMainButtons() {
  const buttonsContainer = document.getElementById('panel-buttons');
  if (!buttonsContainer) {
    console.error('[Augment Auto] Buttons container not found!');
    return;
  }
  
  // 清空现有按钮
  buttonsContainer.innerHTML = '';
  
  // 按钮1: 立即注册（仅注册）
  const btn1 = document.createElement('button');
  btn1.className = 'action-card card-register';
  btn1.innerHTML = `
    <div class="card-icon">🚀</div>
    <div class="card-title">立即注册（仅注册）</div>
    <div class="card-desc">自动完成注册流程</div>
  `;
  btn1.addEventListener('click', async () => {
    const { users, emails } = await chrome.storage.local.get(['users', 'emails']);
    if (!emails || emails.length === 0) {
      showNotification('❌ 请先添加邮箱');
      return;
    }
    if (!users || users.length === 0) {
      showNotification('❌ 请先添加用户信息');
      return;
    }
    updateStatus('开始注册流程...');
    chrome.runtime.sendMessage({
      action: 'registerOnly',
      data: { user: users[0], email: emails[0] }
    });
  });
  buttonsContainer.appendChild(btn1);
  
  // 按钮2: 全流程绑卡
  const btn2 = document.createElement('button');
  btn2.className = 'action-card card-bind';
  btn2.innerHTML = `
    <div class="card-icon">⚡</div>
    <div class="card-title">全流程绑卡</div>
    <div class="card-desc">Dashboard → 自动绑卡</div>
  `;
  btn2.addEventListener('click', async () => {
    const { cards, users } = await chrome.storage.local.get(['cards', 'users']);
    if (!cards || cards.length === 0) {
      showNotification('❌ 请先添加卡信息');
      return;
    }
    if (!users || users.length === 0) {
      showNotification('❌ 请先添加用户信息');
      return;
    }
    updateStatus('开始绑卡流程...');
    chrome.runtime.sendMessage({
      action: 'bindCardOnly',
      data: { card: cards[0], user: users[0] }
    });
  });
  buttonsContainer.appendChild(btn2);
  
  // 按钮3: 立即注册+全流程绑卡
  const btn3 = document.createElement('button');
  btn3.className = 'action-card card-all';
  btn3.innerHTML = `
    <div class="card-icon">🎯</div>
    <div class="card-title">立即注册+全流程绑卡</div>
    <div class="card-desc">注册完成 → 自动绑卡</div>
  `;
  btn3.addEventListener('click', async () => {
    const { cards, users, emails } = await chrome.storage.local.get(['cards', 'users', 'emails']);
    if (!emails || emails.length === 0) {
      showNotification('❌ 请先添加邮箱');
      return;
    }
    if (!users || users.length === 0) {
      showNotification('❌ 请先添加用户信息');
      return;
    }
    if (!cards || cards.length === 0) {
      showNotification('❌ 请先添加卡信息');
      return;
    }
    updateStatus('开始完整流程...');
    chrome.runtime.sendMessage({
      action: 'registerAndBind',
      data: { card: cards[0], user: users[0], email: emails[0] }
    });
  });
  buttonsContainer.appendChild(btn3);
  
  console.log('[Augment Auto] Main buttons added');
}

function updateStatus(text) {
  const status = document.getElementById('panel-status');
  if (status) status.textContent = text;
}

// ========== 登录成功 - Subscription页面处理 ==========

// {{ AURA-X: Modify - 复用主页按钮功能. Approval: 寸止 }}
async function handleSubscriptionPage(data) {
  console.log('[Augment Auto] Handling subscription page');
  
  await wait(1500);
  
  updateStatus('账号信息自动获取中...');
  
  // {{ AURA-X: Modify - 显示9个按钮. Approval: 寸止 }}
  // 自动获取账号信息
  await fetchSubscriptionInfo();
  
  // 显示统一的9个按钮
  await handleAuthPage(data);
  
  updateStatus('页面已就绪');
}

// {{ AURA-X: Add - 辅助函数提取tenant URL. Approval: 寸止 }}
function extractTenantFromApi(data) {
  // 尝试从不同可能的字段中提取tenant URL
  if (data.tenant) {
    if (typeof data.tenant === 'string') return data.tenant;
    if (data.tenant.url) return data.tenant.url;
    if (data.tenant.apiUrl) return data.tenant.apiUrl;
  }
  
  // 尝试从portalUrl中提取
  if (data.portalUrl && data.portalUrl.includes('portal.withorb.com')) {
    return data.portalUrl.match(/d\d+\.api\.augmentcode\.com/)?.[0] || 'Unknown';
  }
  
  return 'Unknown';
}

// {{ AURA-X: Modify - 使用当前页面的_session调用API. Approval: 寸止 }}
/**
 * 步骤2: 从subscription页面获取完整账号信息并保存
 * 读取: tempAccountData (email, tenant_url, auth_session, code, state)
 * 调用: /api/subscription, /api/credits (使用当前页面的_session)
 * 保存: 完整账号信息到 registeredAccounts
 */
async function fetchSubscriptionInfo() {
  try {
    updateStatus('Step 2: 正在获取完整账号信息...');

    // 读取暂存的账号数据
    const { tempAccountData } = await chrome.storage.local.get(['tempAccountData']);

    if (!tempAccountData) {
      console.warn('[Step 2] No temp account data found');
      showNotification('⚠️ 未找到暂存数据\n请先在auth/continue页面提取信息');
      return;
    }

    console.log('[Step 2] ✅ LOADED TEMP DATA');
    console.log('[Step 2] Email:', tempAccountData.email);
    console.log('[Step 2] Tenant URL:', tempAccountData.tenant_url);

    // 获取当前页面(app.augmentcode.com)的_session用于调用接口
    let appSession = null;
    try {
      const response = await chrome.runtime.sendMessage({ action: 'getCookies' });
      appSession = response?.session;
      console.log('[Step 2] Got app _session for API calls');
    } catch (e) {
      console.warn('[Step 2] Failed to get app session:', e);
    }

    // 使用当前页面的_session构建header
    const sessionHeader = appSession ? { 'Cookie': `_session=${appSession}` } : {};

    console.log('[Step 2] Calling /api/subscription with app _session...');

    // 调用 /api/subscription 接口
    const response = await fetch('https://app.augmentcode.com/api/subscription', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        ...sessionHeader
      }
    });

    if (!response.ok) {
      throw new Error(`API返回错误: ${response.status}`);
    }

    const subscriptionData = await response.json();
    console.log('[Step 2] Subscription data:', subscriptionData);

    // 调用 /api/credits 接口获取更准确的credit信息
    let creditsData = null;
    try {
      const creditsRes = await fetch('https://app.augmentcode.com/api/credits', {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          ...sessionHeader
        }
      });
      if (creditsRes.ok) {
        creditsData = await creditsRes.json();
        console.log('[Step 2] Credits data:', creditsData);
      }
    } catch (e) {
      console.warn('[Step 2] Failed to get credits:', e);
    }

    // {{ AURA-X: Modify - 组合完整账号信息. Approval: 寸止 }}
    // 组合：暂存数据 + API数据 = 完整账号信息
    const fullAccountInfo = {
      id: Date.now(),
      // 从 tempAccountData
      email: tempAccountData.email,
      tenant_url: tempAccountData.tenant_url,
      auth_session: tempAccountData.auth_session,  // 保存auth.augmentcode.com的session用于标识账号
      code: tempAccountData.code,
      state: tempAccountData.state,
      registeredAt: tempAccountData.registeredAt,
      timestamp: tempAccountData.timestamp,
      // 从 API
      portalUrl: subscriptionData.portalUrl || subscriptionData.portal_url || '',
      credits: creditsData?.remaining || creditsData?.credits || 0,
      totalCredits: creditsData?.total || 30000,
      usedCredits: creditsData?.used || 0,
      planName: subscriptionData.plan?.name || subscriptionData.planName || 'Free Plan',
      nextBillingDate: subscriptionData.plan?.billingPeriodEnd ||
                       subscriptionData.nextBillingDate || '',
      // 元数据
      source: 'two_step_flow',
      fetchedAt: new Date().toLocaleString()
    };

    console.log('[Step 2] ✅ FULL ACCOUNT INFO SAVED');
    console.log('[Step 2] Email:', fullAccountInfo.email);
    console.log('[Step 2] Tenant URL:', fullAccountInfo.tenant_url);
    console.log('[Step 2] Credits:', fullAccountInfo.credits);

    // 保存到 registeredAccounts
    const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);

    // 检查是否已存在（通过email去重）
    const existingIndex = registeredAccounts.findIndex(acc => acc.email === fullAccountInfo.email);

    if (existingIndex >= 0) {
      // 更新现有账号
      registeredAccounts[existingIndex] = fullAccountInfo;
      console.log('[Step 2] Account updated at index:', existingIndex);
      showNotification(`✅ 账号信息已更新\n邮箱: ${fullAccountInfo.email}\n剩余: ${fullAccountInfo.credits} credits`);
    } else {
      // 新增账号
      registeredAccounts.push(fullAccountInfo);
      console.log('[Step 2] New account added, total:', registeredAccounts.length);
      showNotification(`✅ 账号已保存\n邮箱: ${fullAccountInfo.email}\n剩余: ${fullAccountInfo.credits} credits`);
    }

    await chrome.storage.local.set({ registeredAccounts });

    // 清除临时数据
    await chrome.storage.local.remove(['tempAccountData']);
    console.log('[Step 2] Temp data cleared, account saved successfully');

    updateStatus('账号信息已完整保存');
    copyToClipboard(fullAccountInfo.auth_session || '');

  } catch (error) {
    console.error('[Step 2] Failed to fetch subscription info:', error);
    showNotification('❌ 获取失败: ' + error.message);
    updateStatus('获取失败');
  }
}

// ========== 注册成功页面处理 ==========

// {{ AURA-X: Modify - 先检测验证失败，再提取账号. Approval: 寸止 }}
async function handleRegistrationSuccess(data) {
  console.log('[Augment Auto] Handling registration success page');

  await wait(500);

  // {{ AURA-X: Add - 先检测验证失败. Approval: 寸止 }}
  // 检查是否有验证失败的错误提示
  const verificationError = document.querySelector('.text-red-100');
  if (verificationError && verificationError.textContent.includes('Verification failed')) {
    console.error('[Augment Auto] Verification failed detected on auth/continue page!');
    showNotification('❌ 验证失败\n正在删除邮箱并重试...');
    updateStatus('验证失败，准备重试');

    // 删除使用的邮箱
    const { currentUsedEmail } = await chrome.storage.local.get(['currentUsedEmail']);
    if (currentUsedEmail) {
      await removeUsedEmail(currentUsedEmail);
      await chrome.storage.local.remove(['currentUsedEmail']);
      console.log('[Augment Auto] Failed email removed:', currentUsedEmail);
      showNotification(`✅ 邮箱已删除: ${currentUsedEmail}`);
    }

    // 等待2秒后跳转回注册首页重新执行
    setTimeout(async () => {
      // 检查是否还有可用邮箱
      const { emails = [] } = await chrome.storage.local.get(['emails']);

      if (emails.length === 0) {
        showNotification('❌ 没有可用邮箱了\n请添加新的邮箱');
        updateStatus('没有可用邮箱');
        await handleAuthPage(data);
        return;
      }

      showNotification(`✅ 正在跳转重试（剩余${emails.length}个邮箱）`);
      updateStatus('跳转到注册页面');

      // 跳转回注册首页
      const { codeVerifier, state } = await chrome.storage.local.get(['codeVerifier', 'state']);

      // 计算code_challenge
      const encoder = new TextEncoder();
      const dataToHash = encoder.encode(codeVerifier);
      const hashBuffer = await crypto.subtle.digest('SHA-256', dataToHash);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashBase64 = btoa(String.fromCharCode(...hashArray));
      const codeChallenge = hashBase64
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');

      const registerUrl = `https://auth.augmentcode.com/authorize?response_type=code&code_challenge=${codeChallenge}&client_id=v&state=${state}&prompt=login`;

      console.log('[Augment Auto] Redirecting to register page:', registerUrl);
      window.location.href = registerUrl;
    }, 2000);

    // 显示按钮但不继续处理
    await handleAuthPage(data);
    return;
  }

  // 查找codeDisplay输入框
  const codeDisplay = document.querySelector('input#codeDisplay');
  const url = window.location.href;

  // {{ AURA-X: Modify - 特别处理 complete-signup 页面. Approval: 寸止 }}
  if (!codeDisplay && !url.includes('/complete-signup')) {
    console.error('[Augment Auto] Code display not found');
    updateStatus('未找到授权码');
    await handleAuthPage(data);
    return;
  }

  // {{ AURA-X: Add - 检测/onboard页面并点击Skip for now. Approval: 寸止 }}
  // 检测是否在/onboard页面
  if (url.includes('/onboard')) {
    console.log('[Augment Auto] Detected /onboard page, monitoring for Skip for now button...');
    monitorAndClickSkipForNow();
    return;
  }

  updateStatus('正在提取账号信息...');

  // {{ AURA-X: Modify - 显示9个按钮. Approval: 寸止 }}
  // 自动提取
  if (url.includes('/complete-signup')) {
    // complete-signup 页面特殊处理：直接通过 session 获取信息
    await extractSessionFromCompleteSignup(data);
  } else {
    await extractAndSaveAccountInfo(codeDisplay, data);
  }

  // 显示统一的9个按钮
  await handleAuthPage(data);

  updateStatus('注册成功！账号已保存');
}

// {{ AURA-X: Modify - 重构为在auth页面提取session，然后打开新窗口. Approval: 寸止 }}
/**
 * 步骤1: 从 auth/continue 页面提取账号信息并暂存
 * 提取: tenant_url, code, state (from codeDisplay)
 * 提取: session (from auth.augmentcode.com cookie)
 * 暂存到: tempAccountData
 * 然后: 打开新窗口跳转到app.augmentcode.com/account/subscription
 */
async function extractAndSaveAccountInfo(codeDisplay, userData) {
  try {
    const value = codeDisplay.value;
    console.log('[Step 1] Raw JSON value from codeDisplay:', value.substring(0, 100));

    // 解码HTML转义的JSON
    const jsonString = value
      .replace(/&quot;/g, '"')
      .replace(/&amp;/g, '&')
      .replace(/&lt;/g, '<')
      .replace(/&gt;/g, '>');

    const authData = JSON.parse(jsonString);
    console.log('[Step 1] Parsed auth data:', authData);

    // 提取关键信息
    const { currentUsedEmail } = await chrome.storage.local.get(['currentUsedEmail']);
    const email = currentUsedEmail || userData?.email?.email || userData?.email?.address || 'Unknown';
    const tenantUrl = authData.tenant_url || 'Unknown';
    const code = authData.code;
    const state = authData.state;

    console.log('[Step 1] Extracted from codeDisplay:', { email, tenantUrl, code: code?.substring(0, 20), state: state?.substring(0, 20) });

    // 从auth.augmentcode.com的Cookie获取session
    let authSession = null;
    try {
      authSession = await fetchAuthSessionFromCookie();
    } catch (e) {
      console.warn('[Step 1] Failed to fetch auth session from cookie:', e);
    }



    // 检查是否已存在
    const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
    const existingAccount = registeredAccounts.find(acc => acc.email === email);

    if (existingAccount) {
      console.log('[Step 1] Account already exists, skipping...');
      showNotification(`⚠️ 账号已存在\n邮箱: ${email}`);
      return;
    }

    // 暂存到 tempAccountData
    const tempData = {
      email,
      tenant_url: tenantUrl,
      auth_session: authSession,  // 这是auth.augmentcode.com的session
      code,
      state,
      registeredAt: new Date().toLocaleString(),
      timestamp: Date.now()
    };

    await chrome.storage.local.set({ tempAccountData: tempData });

    console.log('[Step 1] ✅ TEMP DATA SAVED');
    console.log('[Step 1] Email:', tempData.email);
    console.log('[Step 1] Tenant URL:', tempData.tenant_url);
    console.log('[Step 1] Auth Session:', tempData.auth_session);
    console.log('[Step 1] Code:', tempData.code);
    console.log('[Step 1] State:', tempData.state);

    showNotification(`✅ 信息已提取\n邮箱: ${email}\n正在打开新窗口跳转...`);
    updateStatus('信息已暂存，打开新窗口');

    // 删除已使用的邮箱
    if (currentUsedEmail) {
      await removeUsedEmail(currentUsedEmail);
      await chrome.storage.local.remove(['currentUsedEmail']);
      console.log('[Step 1] Used email removed:', currentUsedEmail);
    }

    // 打开新窗口跳转到subscription页面
    setTimeout(() => {
      const subscriptionUrl = 'https://app.augmentcode.com/account/subscription';
      console.log('[Step 1] Opening new window to:', subscriptionUrl);
      window.open(subscriptionUrl, '_blank');
    }, 1000);

  } catch (error) {
    console.error('[Step 1] Failed to extract:', error);
    showNotification('❌ 提取失败: ' + error.message);
  }
}

// {{ AURA-X: Add - 特别处理 complete-signup 页面. Approval: 寸止 }}
/**
 * 特别处理 complete-signup 页面
 * 这个页面没有 codeDisplay 元素，需要从 URL 或其他来源提取信息
 */
async function extractSessionFromCompleteSignup(userData) {
  try {
    console.log('[Complete Signup] Extracting session from complete-signup page');

    // 检查是否有验证失败的错误提示（与 handleRegistrationSuccess 保持一致）
    const verificationError = document.querySelector('.text-red-100');
    if (verificationError && verificationError.textContent.includes('Verification failed')) {
      console.error('[Augment Auto] Verification failed detected on complete-signup page!');
      showNotification('❌ 验证失败\n正在删除邮箱并重试...');
      updateStatus('验证失败，准备重试');

      // 删除使用的邮箱
      const { currentUsedEmail } = await chrome.storage.local.get(['currentUsedEmail']);
      if (currentUsedEmail) {
        await removeUsedEmail(currentUsedEmail);
        await chrome.storage.local.remove(['currentUsedEmail']);
        console.log('[Augment Auto] Failed email removed:', currentUsedEmail);
        showNotification(`✅ 邮箱已删除: ${currentUsedEmail}`);
      }

      // 等待2秒后跳转回注册首页重新执行
      setTimeout(async () => {
        // 检查是否还有可用邮箱
        const { emails = [] } = await chrome.storage.local.get(['emails']);

        if (emails.length === 0) {
          showNotification('❌ 没有可用邮箱了\n请添加新的邮箱');
          updateStatus('没有可用邮箱');
          return;
        }

        showNotification(`✅ 正在跳转重试（剩余${emails.length}个邮箱）`);
        updateStatus('跳转到注册页面');

        // 跳转回注册首页
        const { codeVerifier, state } = await chrome.storage.local.get(['codeVerifier', 'state']);

        // 计算code_challenge
        const encoder = new TextEncoder();
        const dataToHash = encoder.encode(codeVerifier);
        const hashBuffer = await crypto.subtle.digest('SHA-256', dataToHash);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashBase64 = btoa(String.fromCharCode(...hashArray));
        const codeChallenge = hashBase64
          .replace(/\+/g, '-')
          .replace(/\//g, '_')
          .replace(/=/g, '');

        const registerUrl = `https://auth.augmentcode.com/authorize?response_type=code&code_challenge=${codeChallenge}&client_id=v&state=${state}&prompt=login`;

        console.log('[Augment Auto] Redirecting to register page:', registerUrl);
        window.location.href = registerUrl;
      }, 2000);

      return; // 不继续处理
    }

    // {{ AURA-X: Add - 打印暂存数据和auth session. Approval: 寸止 }}
    // 打印暂存的数据
    console.log('[Complete Signup] ✅ TEMP DATA FROM STORAGE');
    console.log('[Complete Signup] Email:', userData?.email?.email || userData?.email?.address);
    console.log('[Complete Signup] Tenant URL:', userData?.tenant_url);
    console.log('[Complete Signup] Auth Session:', userData?.auth_session);
    console.log('[Complete Signup] Code:', userData?.code);
    console.log('[Complete Signup] State:', userData?.state);

    // 从auth.augmentcode.com的Cookie获取session
    let session = null;
    try {
      const response = await chrome.runtime.sendMessage({ action: 'getAuthSessionCookie' });
      if (response && response.success && response.session) {
        session = response.session;
        console.log('[Complete Signup] ✅ Got auth session from cookie');
        console.log('[Complete Signup] Session:', session);
      } else {
        console.warn('[Complete Signup] Failed to get auth session:', response?.error);
      }
    } catch (e) {
      console.warn('[Complete Signup] Failed to fetch session:', e);
    }

    // 从URL获取查询参数
    const urlParams = new URLSearchParams(window.location.search);
    const paymentVerified = urlParams.get('payment_verified');

    // 获取当前使用的邮箱
    const { currentUsedEmail } = await chrome.storage.local.get(['currentUsedEmail']);
    const email = currentUsedEmail || userData?.email?.email || userData?.email?.address || 'Unknown';

    // {{ AURA-X: Modify - 只从DOM中提取tenant_url，不调用API. Approval: 寸止 }}
    // 在complete-signup页面上，只做信息提取暂存，不调用API
    // 因为这个页面没有app.augmentcode.com的_session，调用API会401
    let tenantUrl = 'Unknown';

    // 从codeDisplay input元素的value中提取JSON
    try {
      const codeDisplay = document.getElementById('codeDisplay');
      if (codeDisplay && codeDisplay.value) {
        console.log('[Complete Signup] Found codeDisplay element');
        const jsonData = JSON.parse(codeDisplay.value);
        if (jsonData.tenant_url) {
          tenantUrl = jsonData.tenant_url;
          console.log('[Complete Signup] ✅ Extracted tenant_url from DOM:', tenantUrl);
        }
      }
    } catch (e) {
      console.warn('[Complete Signup] Failed to parse codeDisplay JSON:', e);
    }

    if (tenantUrl === 'Unknown') {
      console.log('[Complete Signup] ⚠️ Could not extract tenant_url from DOM, will be set to Unknown');
    }

    console.log('[Complete Signup] Extracted:', { email, tenantUrl, hasSession: !!session, paymentVerified });

    // 检查是否已存在
    const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
    const existingAccount = registeredAccounts.find(acc => acc.email === email);

    if (existingAccount) {
      console.log('[Complete Signup] Account already exists, skipping...');
      showNotification(`⚠️ 账号已存在\n邮箱: ${email}`);
      return;
    }

    // {{ AURA-X: Modify - 统一字段名为auth_session. Approval: 寸止 }}
    // 暂存到 tempAccountData
    const tempData = {
      email,
      tenant_url: tenantUrl,
      auth_session: session,  // 统一使用auth_session字段名，与handleRegistrationSuccess保持一致
      code: null, // complete-signup 页面可能没有code
      state: null, // complete-signup 页面可能没有state
      registeredAt: new Date().toLocaleString(),
      timestamp: Date.now(),
      payment_verified: paymentVerified === 'true'
    };

    await chrome.storage.local.set({ tempAccountData: tempData });

    console.log('[Complete Signup] Temp data saved:', tempData);
    console.log('[Complete Signup] Auth Session:', tempData.auth_session);
    showNotification(`✅ 信息已提取\n邮箱: ${email}\nTenant: ${tenantUrl}\n正在跳转到subscription页面...`);
    updateStatus('信息已暂存，即将跳转');

    // 删除已使用的邮箱
    if (currentUsedEmail) {
      await removeUsedEmail(currentUsedEmail);
      await chrome.storage.local.remove(['currentUsedEmail']);
      console.log('[Complete Signup] Used email removed:', currentUsedEmail);
    }

    // 发送 stepComplete 消息，触发跳转
    chrome.runtime.sendMessage({
      action: 'stepComplete',
      step: 'register'
    });

  } catch (error) {
    console.error('[Complete Signup] Failed to extract:', error);
    showNotification('❌ 提取失败: ' + error.message);
  }
}

// {{ AURA-X: Add - 从auth.augmentcode.com获取session. Approval: 寸止 }}
/**
 * 从auth.augmentcode.com的cookie中获取session
 * 这是第4步中需要的session，用于后续API调用
 */
async function fetchAuthSessionFromCookie() {
  try {
    // 通过background script获取auth.augmentcode.com的Cookie
    const response = await chrome.runtime.sendMessage({
      action: 'getAuthCookies',
      domain: 'auth.augmentcode.com'
    });

    if (response && response.session) {
      console.log('[Step 1] ✅ Got auth session:', response.session);
      return response.session;
    }

    console.warn('[Step 1] ❌ Auth session not found');
    return null;
  } catch (error) {
    console.error('[Step 1] Failed to fetch auth session:', error);
    return null;
  }
}

// 获取Access Token - 方法1: 通过Cookie获取session (已弃用，保留向后兼容)
async function fetchAccessToken() {
  try {
    // 通过background script获取Cookie
    const response = await chrome.runtime.sendMessage({ action: 'getCookies' });

    if (response && response.session) {
      console.log('[Augment Auto] Found session cookie:', response.session.substring(0, 30) + '...');
      return response.session;
    }

    console.warn('[Augment Auto] Session cookie not found');
    return null;
  } catch (error) {
    console.error('[Augment Auto] Failed to fetch token:', error);
    return null;
  }
}

// {{ AURA-X: Modify - 优化邮箱删除逻辑，支持多种格式. Approval: 寸止 }}
async function removeUsedEmail(email) {
  try {
    const { emails = [] } = await chrome.storage.local.get(['emails']);
    
    // 标准化输入邮箱
    const targetEmail = typeof email === 'string' ? email : (email?.email || email?.address || '');
    
    console.log('[Augment Auto] Removing email:', targetEmail);
    console.log('[Augment Auto] Current emails:', emails.map(e => e.email || e.address || e));
    
    // 过滤：保留不匹配的邮箱
    const filtered = emails.filter(e => {
      const currentEmail = e.email || e.address || e;
      const matches = currentEmail === targetEmail;
      return !matches; // 保留不匹配的
    });
    
    await chrome.storage.local.set({ emails: filtered });
    
    console.log('[Augment Auto] Email removed. Remaining:', filtered.length);
    
    if (filtered.length === emails.length) {
      console.warn('[Augment Auto] No email was removed, target may not exist:', targetEmail);
    }
  } catch (e) {
    console.error('[Augment Auto] Failed to remove email:', e);
  }
}

// 显示已注册账号列表
async function showRegisteredAccounts() {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  
  if (registeredAccounts.length === 0) {
    showNotification('暂无已注册账号');
    return;
  }
  
  const list = registeredAccounts.map((acc, idx) => 
    `${idx + 1}. ${acc.email}\n   注册时间: ${acc.registeredAt}`
  ).join('\n\n');
  
  showNotification(`已注册账号 (${registeredAccounts.length}个):\n\n${list}`);
}

// 复制到剪贴板
function copyToClipboard(text) {
  try {
    navigator.clipboard.writeText(text);
    console.log('[Augment Auto] Copied to clipboard');
  } catch (e) {
    console.error('[Augment Auto] Copy failed:', e);
  }
}

// ========== Stripe绑卡页面处理 ==========

async function handleStripeBillingPage(data) {
  console.log('[Augment Auto] Handling Stripe billing page');
  
  await wait(1500);
  
  // 显示统一的9个按钮
  await handleAuthPage(data);
  
  updateStatus('绑卡页面已就绪');
}

// {{ AURA-X: Add - 自动填写卡片表单. Approval: 寸止 }}
async function autoFillCardForm() {
  try {
    updateStatus('正在读取卡片信息...');
    
    // 1. 从storage读取卡片和用户信息
    const { cards = [], users = [] } = await chrome.storage.local.get(['cards', 'users']);
    
    if (cards.length === 0) {
      showNotification('❌ 没有可用的卡片信息\n请先在主页添加卡片');
      updateStatus('没有卡片信息');
      return;
    }
    
    if (users.length === 0) {
      showNotification('❌ 没有可用的用户信息\n请先在主页添加用户');
      updateStatus('没有用户信息');
      return;
    }
    
    // 2. 使用第一张卡片和第一个用户
    const card = cards[0];
    const user = users[0];
    
    console.log('[Augment Auto] Using card:', card);
    console.log('[Augment Auto] Using user:', user);
    console.log('[Augment Auto] User keys:', Object.keys(user));
    
    updateStatus('正在填写表单...');
    
    // 3. 填写卡片信息
    const cardNumber = document.getElementById('cardNumber');
    const cardExpiry = document.getElementById('cardExpiry');
    const cardCvc = document.getElementById('cardCvc');
    
    if (cardNumber) fillInput(cardNumber, card.number);
    await wait(300);
    
    if (cardExpiry) {
      const expiryValue = `${card.month}/${card.year.substring(2)}`;
      fillInput(cardExpiry, expiryValue);
    }
    await wait(300);
    
    if (cardCvc) fillInput(cardCvc, card.cvc);
    await wait(500);
    
    // 4. 填写账单信息
    const billingName = document.getElementById('billingName');
    const billingCountry = document.getElementById('billingCountry');
    const billingAddressLine1 = document.getElementById('billingAddressLine1');
    const billingAddressLine2 = document.getElementById('billingAddressLine2');
    const billingLocality = document.getElementById('billingLocality');
    const billingAdministrativeArea = document.getElementById('billingAdministrativeArea');
    const billingPostalCode = document.getElementById('billingPostalCode');
    
    // {{ AURA-X: Modify - 修正用户字段映射. Approval: 寸止 }}
    const userName = user['全名'] || user.name || user.fullName || '';
    console.log('[Augment Auto] User name to fill:', userName);
    if (billingName && userName) fillInput(billingName, userName);
    await wait(300);
    
    // 设置国家为台湾
    if (billingCountry) {
      billingCountry.value = 'TW';
      billingCountry.dispatchEvent(new Event('change', { bubbles: true }));
    }
    await wait(800);
    
    if (billingAddressLine1) fillInput(billingAddressLine1, user['地址第 1 行'] || user.addressLine1);
    await wait(300);
    
    const addressLine2 = user['地址第 2 行'] || user.addressLine2;
    if (billingAddressLine2 && addressLine2) {
      fillInput(billingAddressLine2, addressLine2);
      await wait(300);
    }
    
    // 填写城市（地區）
    const cityValue = user['地區'] || user.district || '';
    console.log('[Augment Auto] City to fill:', cityValue);
    if (billingLocality && cityValue) fillInput(billingLocality, cityValue);
    await wait(300);
    
    // 填写省/县（縣）
    const areaValue = user['縣'] || user.county || '';
    console.log('[Augment Auto] Area to fill:', areaValue);
    if (billingAdministrativeArea && areaValue) {
      billingAdministrativeArea.value = areaValue;
      billingAdministrativeArea.dispatchEvent(new Event('change', { bubbles: true }));
    }
    await wait(300);
    
    // 填写郵遞區號
    const postalValue = user['郵遞區號'] || user.postalCode || '';
    console.log('[Augment Auto] Postal code to fill:', postalValue);
    if (billingPostalCode && postalValue) fillInput(billingPostalCode, postalValue);
    await wait(500);
    
    showNotification('✅ 表单填写完成！\n3秒后自动提交...');
    updateStatus('表单填写完成，准备提交');
    
    // 5. 自动提交表单
    setTimeout(async () => {
      const submitBtn = document.querySelector('button[data-testid="hosted-payment-submit-button"]');
      if (submitBtn && submitBtn.classList.contains('SubmitButton--complete')) {
        // 按钮可用，点击提交
        console.log('[Augment Auto] Clicking submit button...');
        submitBtn.click();
        updateStatus('正在提交卡片...');
        showNotification('✅ 正在提交卡片验证...');
        
        // 6. 监听验证结果
        await monitorCardVerification();
      } else {
        console.warn('[Augment Auto] Submit button not ready');
        showNotification('❌ 提交按钮未就绪\n请手动点击"儲存卡"');
      }
    }, 3000);
    
  } catch (error) {
    console.error('[Augment Auto] Failed to fill card form:', error);
    showNotification('❌ 填写表单失败\n' + error.message);
    updateStatus('填写失败');
  }
}

// {{ AURA-X: Modify - 移除超时限制，一直等待直到有结果. Approval: 寸止 }}
async function monitorCardVerification() {
  console.log('[Augment Auto] Monitoring card verification...');
  
  let wasProcessing = false;
  
  const checkInterval = setInterval(async () => {
    const submitBtn = document.querySelector('button[data-testid="hosted-payment-submit-button"]');
    
    if (!submitBtn) {
      console.warn('[Augment Auto] Submit button not found, continue waiting...');
      return;
    }
    
    // 检查按钮状态
    const isProcessing = submitBtn.classList.contains('SubmitButton--processing') || 
                        submitBtn.querySelector('.SubmitButton-SpinnerIcon');
    const hasCheckmark = submitBtn.querySelector('.SubmitButton-CheckmarkIcon');
    const isComplete = submitBtn.classList.contains('SubmitButton--complete');
    
    console.log(`[Augment Auto] Button state - Processing: ${isProcessing}, Complete: ${isComplete}, Checkmark: ${!!hasCheckmark}`);
    
    // 记录是否曾经在处理中
    if (isProcessing) {
      wasProcessing = true;
      updateStatus('正在验证卡片...');
    }
    
    // 检查是否验证成功（页面跳转）
    const url = window.location.href;
    const pageRedirected = !url.includes('billing.augmentcode.com') && !url.includes('/c/pay/');
    
    if (pageRedirected) {
      clearInterval(checkInterval);
      console.log('[Augment Auto] Card verification successful! Page redirected.');
      showNotification('✅ 卡片验证成功！\n正在删除已使用的卡片...');
      updateStatus('验证成功，清理数据');
      
      await deleteFirstCard();
      
      showNotification('✅ 绑卡完成！\n已自动删除使用的卡片');
      updateStatus('绑卡完成');
      return;
    }
    
    // 检查是否验证失败（必须先经过processing状态）
    if (wasProcessing && !isProcessing) {
      // Loading消失，检查是否有错误
      const errorElement = document.querySelector('.ConfirmPaymentButton-Error, .FieldError-container[style*="opacity: 1"]');
      const cardNumberField = document.querySelector('#cardNumber');
      const hasFieldError = cardNumberField && cardNumberField.parentElement.querySelector('.FieldError');
      
      if (errorElement || hasFieldError) {
        clearInterval(checkInterval);
        console.error('[Augment Auto] Card verification failed! Error detected after processing.');
        showNotification('❌ 当前卡片验证失败\n正在尝试下一张卡片...');
        updateStatus('卡片失败，尝试下一张');
        
        // 删除失败的卡片
        await deleteFirstCard();
        
        // 检查是否还有卡片
        const { cards = [] } = await chrome.storage.local.get(['cards']);
        
        if (cards.length > 0) {
          showNotification(`📝 还有 ${cards.length} 张卡片\n正在自动重试...`);
          updateStatus('正在使用下一张卡片');
          
          // 等待2秒后自动重试
          await wait(2000);
          await autoFillCardForm();
        } else {
          showNotification('❌ 所有卡片都已失败\n请添加新的卡片信息');
          updateStatus('没有可用卡片');
        }
        return;
      }
      
      // 如果没有错误但也没有对号，可能是其他状态，继续等待
      console.log('[Augment Auto] Processing finished but no error or success detected, continue monitoring...');
    }
  }, 1000);
}

// {{ AURA-X: Add - 只删除第一张卡片，保留用户. Approval: 寸止 }}
async function deleteFirstCard() {
  try {
    const { cards = [] } = await chrome.storage.local.get(['cards']);
    
    if (cards.length > 0) {
      const deletedCard = cards.shift(); // 删除第一张卡片
      await chrome.storage.local.set({ cards });
      console.log('[Augment Auto] Deleted card:', deletedCard.number.substring(0, 4) + '****');
      console.log('[Augment Auto] Remaining cards:', cards.length);
    } else {
      console.warn('[Augment Auto] No cards to delete');
    }
  } catch (error) {
    console.error('[Augment Auto] Failed to delete card:', error);
  }
}

// ========== 注册/授权页面处理 ==========

async function handleAuthPage(data) {
  console.log('[Augment Auto] Handling auth page, data:', data);

  await wait(500);

  // {{ AURA-X: Modify - 确保面板和容器都存在. Approval: 寸止 }}
  // 确保侧边面板已创建
  let panel = document.getElementById('augment-auto-panel');
  if (!panel) {
    console.log('[Augment Auto] Panel not found, creating...');
    createSidePanel();
    await wait(200);
    panel = document.getElementById('augment-auto-panel');
  }

  // 确保按钮容器存在
  let buttonsContainer = document.getElementById('panel-buttons');
  if (!buttonsContainer) {
    console.error('[Augment Auto] Buttons container not found even after creating panel!');
    // 强制重新创建面板
    if (panel) panel.remove();
    createSidePanel();
    await wait(200);
    buttonsContainer = document.getElementById('panel-buttons');
  }

  // 清空现有按钮
  if (buttonsContainer) {
    buttonsContainer.innerHTML = '';
  } else {
    console.error('[Augment Auto] Failed to get buttons container, cannot add buttons');
    return;
  }

  // {{ AURA-X: Modify - 添加持续监听验证失败. Approval: 寸止 }}
  // 添加持续监听验证失败的错误提示（方案A）
  let verificationFailureHandled = false;

  const handleVerificationFailure = async () => {
    if (verificationFailureHandled) return;
    verificationFailureHandled = true;

    console.error('[Augment Auto] Verification failed detected!');
    showNotification('❌ 验证失败\n正在删除邮箱并重试...');
    updateStatus('验证失败，准备重试');

    // 删除使用的邮箱
    const { currentUsedEmail } = await chrome.storage.local.get(['currentUsedEmail']);
    if (currentUsedEmail) {
      await removeUsedEmail(currentUsedEmail);
      await chrome.storage.local.remove(['currentUsedEmail']);
      console.log('[Augment Auto] Failed email removed:', currentUsedEmail);
      showNotification(`✅ 邮箱已删除: ${currentUsedEmail}`);
    }

    // 等待2秒后跳转回注册首页重新执行
    setTimeout(async () => {
      // 检查是否还有可用邮箱
      const { emails = [] } = await chrome.storage.local.get(['emails']);

      if (emails.length === 0) {
        showNotification('❌ 没有可用邮箱了\n请添加新的邮箱');
        updateStatus('没有可用邮箱');
        return;
      }

      showNotification(`✅ 正在跳转重试（剩余${emails.length}个邮箱）`);
      updateStatus('跳转到注册页面');

      // 跳转回注册首页
      const { codeVerifier, state } = await chrome.storage.local.get(['codeVerifier', 'state']);

      // 计算code_challenge
      const encoder = new TextEncoder();
      const dataToHash = encoder.encode(codeVerifier);
      const hashBuffer = await crypto.subtle.digest('SHA-256', dataToHash);
      const hashArray = Array.from(new Uint8Array(hashBuffer));
      const hashBase64 = btoa(String.fromCharCode(...hashArray));
      const codeChallenge = hashBase64
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');

      const registerUrl = `https://auth.augmentcode.com/authorize?response_type=code&code_challenge=${codeChallenge}&client_id=v&state=${state}&prompt=login`;

      console.log('[Augment Auto] Redirecting to register page:', registerUrl);
      window.location.href = registerUrl;
    }, 2000);
  };

  // 初始检测
  const verificationError = document.querySelector('.text-red-100');
  if (verificationError && verificationError.textContent.includes('Verification failed')) {
    await handleVerificationFailure();
  }

  // {{ AURA-X: Add - 持续监听验证失败. Approval: 寸止 }}
  // 添加MutationObserver持续监听错误提示（方案A）
  const failureObserver = new MutationObserver(() => {
    const error = document.querySelector('.text-red-100');
    if (error && error.textContent.includes('Verification failed')) {
      handleVerificationFailure();
    }
  });

  failureObserver.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['class', 'style']
  });

  // 查找邮箱输入框
  const emailInput = document.querySelector('input#username[name="username"]');
  console.log('[Augment Auto] Email input found:', !!emailInput);

  // {{ AURA-X: Modify - 添加9个按钮. Approval: 寸止 }}
  console.log('[Augment Auto] Adding 9 buttons...');

  // {{ AURA-X: Modify - 实时读取邮箱而非使用缓存. Approval: 寸止 }}
  addButton('🚀 立即注册（仅注册）', async () => {
    // 实时读取最新邮箱
    const { emails = [] } = await chrome.storage.local.get(['emails']);
    if (!emails || emails.length === 0) {
      showNotification('❌ 没有邮箱数据');
      return;
    }
    const emailData = { email: emails[0].email || emails[0].address || emails[0] };
    await fillRegistrationForm({ email: emailData });
    updateStatus('已填写，等待验证');
  }, 'card-register');

  addButton('⛔ 停止', () => {
    window.close();
  }, 'card-delete');

  addButton('⚡ 全流程绑卡', async () => {
    showNotification('请先完成注册');
  }, 'card-bind');

  addButton('🎯 立即注册+全流程绑卡', async () => {
    // 实时读取最新邮箱
    const { emails = [] } = await chrome.storage.local.get(['emails']);
    if (!emails || emails.length === 0) {
      showNotification('❌ 没有邮箱数据');
      return;
    }
    const emailData = { email: emails[0].email || emails[0].address || emails[0] };
    await fillRegistrationForm({ email: emailData });
    updateStatus('已填写，等待验证后绑卡');
  }, 'card-all');

  // {{ AURA-X: Modify - 修复绑卡跳转，只通过点击弹窗. Approval: 寸止 }}
  addButton('😀 完整绑卡', async () => {
    const currentUrl = window.location.href;

    // {{ AURA-X: Add - 检查是否在绑卡页面，直接执行填表单. Approval: 寸止 }}
    // 如果已经在绑卡页面，直接执行填表单
    if (currentUrl.includes('billing.augmentcode.com')) {
      console.log('[Augment Auto] Already on billing page, auto-filling form...');
      await autoFillCardForm();
      return;
    }

    // {{ AURA-X: Add - 在subscription页面，检测并点击弹窗. Approval: 寸止 }}
    // 检查是否在subscription页面
    if (currentUrl.includes('/account/subscription')) {
      // 检测"Confirm payment method"弹窗按钮
      const modalContent = document.querySelector('[role="dialog"]');
      const modalTitle = modalContent ? modalContent.querySelector('h1, .modal-title, [class*="Heading"]') : null;
      const confirmBtn = modalContent ? modalContent.querySelector('button') : null;

      console.log('[Augment Auto] Modal detection:', {
        hasModal: !!modalContent,
        hasTitle: !!modalTitle,
        titleText: modalTitle?.textContent,
        hasButton: !!confirmBtn
      });

      if (modalContent && modalTitle && confirmBtn &&
          (modalTitle.textContent.includes('Start your Free Trial') ||
           modalTitle.textContent.includes('Free Trial'))) {
        console.log('[Augment Auto] Found payment modal, clicking confirm button...');
        showNotification('🚀 点击确认按钮，等待跳转...');
        updateStatus('点击确认按钮');

        // 点击Confirm payment method按钮
        confirmBtn.click();

        // 等待5秒检查是否跳转
        setTimeout(() => {
          const newUrl = window.location.href;
          if (newUrl.includes('billing.augmentcode.com')) {
            console.log('[Augment Auto] Redirected to billing page, auto-filling form...');
            setTimeout(() => autoFillCardForm(), 1000);
          } else {
            showNotification('⚠️ 未自动跳转\n请手动点击"Confirm payment method"');
          }
        }, 5000);
        return;
      } else {
        // 没有找到弹窗
        showNotification('⚠️ 未找到支付弹窗\n请确保弹窗已打开，或手动点击"Confirm payment method"');
        return;
      }
    }

    // 其他页面
    showNotification('❌ 请先进入subscription页面\n并打开支付弹窗');
  }, 'card-verify');

  addButton('📧 获取验证码', () => {
    showNotification('请手动获取验证码');
  }, 'card-verify');

  // {{ AURA-X: Modify - 直接调用fetchSubscriptionInfo. Approval: 寸止 }}
  addButton('提取用户信息', async () => {
    await fetchSubscriptionInfo();
  }, 'card-verify');

  addButton('已注册账号', async () => {
    await showRegisteredAccountsModal();
  }, 'card-all');

  if (emailInput && data && data.email) {
    updateStatus('就绪 - 有数据');
  } else {
    updateStatus('就绪 - 无数据');
  }

  console.log('[Augment Auto] All buttons added');
}

// {{ AURA-X: Modify - 保存当前使用的邮箱. Approval: 寸止 }}
async function fillRegistrationForm(data) {
  const emailInput = document.querySelector('input#username[name="username"]');
  
  if (!emailInput) {
    showNotification('❌ 未找到邮箱输入框');
    return;
  }
  
  const emailToFill = data.email.email || data.email;
  console.log('[Augment Auto] Filling email:', emailToFill);
  fillInput(emailInput, emailToFill);
  
  // 保存当前使用的邮箱，用于后续删除
  await chrome.storage.local.set({ currentUsedEmail: emailToFill });
  console.log('[Augment Auto] Saved current used email:', emailToFill);
  
  await wait(500);
  
  // 尝试触发验证框
  tryTriggerCaptcha();
  
  await wait(1000);
  
  showNotification('✅ 邮箱已填写\n⚠️ 请完成人机验证');
  updateStatus('等待人机验证...');
  
  // 监听验证完成
  monitorCaptchaComplete();
}

// 尝试触发人机验证
function tryTriggerCaptcha() {
  console.log('[Augment Auto] Trying to trigger captcha...');
  
  // 查找验证框
  const captchaSelectors = [
    'iframe[src*="challenges.cloudflare.com"]',
    'iframe[src*="turnstile"]',
    '.ulp-auth0-v2-captcha',
    '[data-captcha-provider]',
    '#ulp-auth0-v2-captcha'
  ];
  
  for (const selector of captchaSelectors) {
    const captcha = document.querySelector(selector);
    if (captcha) {
      console.log('[Augment Auto] Found captcha:', selector);
      
      // 尝试点击触发
      try {
        captcha.click();
        
        // 如果是iframe，尝试点击内部
        if (captcha.tagName === 'IFRAME') {
          const rect = captcha.getBoundingClientRect();
          const x = rect.left + rect.width / 2;
          const y = rect.top + rect.height / 2;
          
          const clickEvent = new MouseEvent('click', {
            view: window,
            bubbles: true,
            cancelable: true,
            clientX: x,
            clientY: y
          });
          
          captcha.dispatchEvent(clickEvent);
        }
      } catch (e) {
        console.log('[Augment Auto] Captcha trigger failed:', e);
      }
      
      break;
    }
  }
}

// 监听验证完成
// {{ AURA-X: Modify - 移除超时限制，一直等待直到验证完成. Approval: 寸止 }}
function monitorCaptchaComplete() {
  console.log('[Augment Auto] Monitoring captcha completion...');

  // 检查验证是否完成，一直等待直到完成
  const checkInterval = setInterval(() => {
    const captchaInput = document.querySelector('input[name="captcha"]');

    if (captchaInput && captchaInput.value) {
      console.log('[Augment Auto] Captcha completed!');
      clearInterval(checkInterval);

      showNotification('✅ 验证完成！\n正在自动提交...');
      updateStatus('验证完成，自动提交');

      // 自动点击Continue
      setTimeout(() => {
        const continueBtn = document.querySelector('button[type="submit"][name="action"]');
        if (continueBtn && !continueBtn.disabled) {
          console.log('[Augment Auto] Auto-clicking Continue...');
          continueBtn.click();

          // 监听页面跳转后的"Skip for now"按钮
          monitorAndClickSkipForNow();
        }
      }, 1000);
    }
  }, 500);
}

// {{ AURA-X: Add - 监听并点击"Skip for now"按钮. Approval: 寸止 }}
function monitorAndClickSkipForNow() {
  console.log('[Augment Auto] Monitoring for Skip for now button...');
  let attemptCount = 0;

  const skipCheckInterval = setInterval(() => {
    attemptCount++;

    // 多种选择器策略，从精确到宽松
    let skipBtn = null;

    // 策略1: 精确匹配class和text
    skipBtn = document.querySelector('button[data-accent-color=""][type="button"].rt-reset.rt-BaseButton.rt-r-size-2.rt-variant-solid.rt-Button.btn.btn-ghost');
    if (skipBtn && skipBtn.textContent.includes('Skip for now')) {
      console.log('[Augment Auto] ✅ Found Skip for now button (strategy 1)');
    } else {
      skipBtn = null;
    }

    // 策略2: 查找所有button，通过text内容匹配
    if (!skipBtn) {
      const allButtons = document.querySelectorAll('button');
      for (const btn of allButtons) {
        if (btn.textContent.includes('Skip for now')) {
          skipBtn = btn;
          console.log('[Augment Auto] ✅ Found Skip for now button (strategy 2 - text match)');
          break;
        }
      }
    }

    // 策略3: 查找包含"Skip"的button
    if (!skipBtn) {
      const allButtons = document.querySelectorAll('button');
      for (const btn of allButtons) {
        if (btn.textContent.includes('Skip')) {
          console.log('[Augment Auto] Found button with "Skip":', btn.textContent.trim());
          if (btn.textContent.includes('for now')) {
            skipBtn = btn;
            console.log('[Augment Auto] ✅ Found Skip for now button (strategy 3)');
            break;
          }
        }
      }
    }

    if (skipBtn) {
      console.log('[Augment Auto] Found Skip for now button, clicking...');
      clearInterval(skipCheckInterval);

      showNotification('✅ 检测到Skip按钮，正在点击...');
      updateStatus('点击Skip for now');

      skipBtn.click();
      console.log('[Augment Auto] Skip for now button clicked');
    } else if (attemptCount % 10 === 0) {
      // 每5秒打印一次日志（10 * 500ms）
      console.log(`[Augment Auto] Still monitoring for Skip for now button... (attempt ${attemptCount})`);
    }
  }, 500);

  // 60秒后停止监听（增加到60秒，给更多时间）
  setTimeout(() => {
    clearInterval(skipCheckInterval);
    console.log('[Augment Auto] Stopped monitoring for Skip for now after 60 seconds');
  }, 60000);
}

// 监听Continue按钮
function monitorContinueButton() {
  const continueBtn = document.querySelector('button[type="submit"][name="action"]');
  
  if (continueBtn) {
    continueBtn.addEventListener('click', () => {
      console.log('[Augment Auto] Continue clicked');
      updateStatus('正在提交...');
      
      setTimeout(() => {
        checkRegistrationSuccess();
      }, 3000);
    });
  }
}

// 检查注册是否成功
async function checkRegistrationSuccess() {
  const url = window.location.href;
  
  if (url.includes('/dashboard') || url.includes('/welcome')) {
    console.log('[Augment Auto] Registration successful!');
    showNotification('✅ 注册成功！');
    updateStatus('注册成功');
    
    chrome.runtime.sendMessage({
      action: 'stepComplete',
      step: 'register'
    });
  }
}

// ========== 绑卡页面处理 ==========

async function handleBillingPage(data) {
  console.log('[Augment Auto] Handling billing page');
  
  await wait(2000);
  
  if (!data || !data.card) {
    showNotification('❌ 没有卡信息数据');
    return;
  }
  
  // {{ AURA-X: Modify - 添加9个按钮. Approval: 寸止 }}
  // 添加统一的9个按钮
  await handleAuthPage(data);
  
  updateStatus('就绪');
}

async function fillCardInfo(card) {
  console.log('[Augment Auto] Filling card info');
  
  const cardNumberInput = findInput([
    'input[name="cardnumber"]',
    'input[name="card-number"]',
    'input[placeholder*="card number" i]',
    'input[autocomplete="cc-number"]'
  ]);
  
  if (cardNumberInput) {
    fillInput(cardNumberInput, card.number);
    await wait(300);
  }
  
  // 月份
  const monthInput = findInput([
    'input[name="exp-month"]',
    'input[placeholder*="mm" i]',
    'select[name="month"]'
  ]);
  
  if (monthInput) {
    fillInput(monthInput, card.month);
    await wait(200);
  }
  
  // 年份
  const yearInput = findInput([
    'input[name="exp-year"]',
    'input[placeholder*="yy" i]',
    'select[name="year"]'
  ]);
  
  if (yearInput) {
    fillInput(yearInput, card.year);
    await wait(200);
  }
  
  // CVC
  const cvcInput = findInput([
    'input[name="cvc"]',
    'input[name="cvv"]',
    'input[placeholder*="cvc" i]'
  ]);
  
  if (cvcInput) {
    fillInput(cvcInput, card.cvc);
  }
  
  showNotification('✅ 卡信息已填写');
  updateStatus('卡信息已填写');
}

async function handleBindingComplete(data) {
  if (data && data.card) {
    const { deleteAfterSuccess } = await chrome.storage.local.get(['deleteAfterSuccess']);
    if (deleteAfterSuccess) {
      await deleteUsedCard(data.card.id);
      showNotification('✅ 绑卡成功，卡信息已删除');
    } else {
      showNotification('✅ 绑卡成功');
    }
    
    chrome.runtime.sendMessage({
      action: 'stepComplete',
      step: 'bind'
    });
  }
  
  updateStatus('绑卡成功');
}

// 删除已使用的卡
async function deleteUsedCard(cardId) {
  const { cards = [] } = await chrome.storage.local.get(['cards']);
  const filtered = cards.filter(c => c.id !== cardId);
  await chrome.storage.local.set({ cards: filtered });
  console.log('[Augment Auto] Card deleted after binding');
}

// 删除第一张卡
async function deleteFirstCard() {
  const { cards = [] } = await chrome.storage.local.get(['cards']);
  if (cards.length > 0) {
    const filtered = cards.slice(1);
    await chrome.storage.local.set({ cards: filtered });
    showNotification('✅ 已删除一张卡');
  } else {
    showNotification('❌ 没有卡信息');
  }
}

// 导航到绑卡页面
function navigateToBilling() {
  window.location.href = 'https://www.augmentcode.com/dashboard/billing';
}

// ========== 工具函数 ==========

function findInput(selectors) {
  for (const selector of selectors) {
    const input = document.querySelector(selector);
    if (input) return input;
  }
  return null;
}

function fillInput(input, value) {
  input.focus();
  input.value = value;
  
  // 触发各种事件
  input.dispatchEvent(new Event('input', { bubbles: true }));
  input.dispatchEvent(new Event('change', { bubbles: true }));
  input.dispatchEvent(new Event('blur', { bubbles: true }));
  
  // React兼容
  const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
  nativeSetter.call(input, value);
  input.dispatchEvent(new Event('input', { bubbles: true }));
}

function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// {{ AURA-X: Add - 手动提取用户信息. Approval: 寸止 }}
async function manuallyExtractUserInfo() {
  try {
    updateStatus('正在提取Session...');
    
    // 1. 从Cookie获取_session
    const response = await chrome.runtime.sendMessage({ action: 'getCookies' });
    
    if (!response || !response.session) {
      showNotification('❌ 未找到session Cookie\n请先登录Augment账户');
      updateStatus('未找到session Cookie');
      return;
    }
    
    const sessionValue = response.session;
    console.log('[Augment Auto] Session from domain:', response.domain);
    console.log('[Augment Auto] Session length:', sessionValue.length);
    console.log('[Augment Auto] Session preview:', sessionValue.substring(0, 100) + '...');
    console.log('[Augment Auto] Full session value:', sessionValue);
    
    updateStatus('正在调用API...');
    
    // 2. 调用 /api/subscription 接口
    const apiResponse = await fetch('https://app.augmentcode.com/api/subscription', {
      method: 'GET',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      credentials: 'include'
    });
    
    if (!apiResponse.ok) {
      showNotification('❌ API调用失败: ' + apiResponse.status);
      updateStatus('API调用失败');
      return;
    }
    
    const subscriptionData = await apiResponse.json();
    console.log('[Augment Auto] Subscription data:', subscriptionData);
    
    // 3. 获取portalUrl并调用
    const portalUrl = subscriptionData.portalUrl || subscriptionData.portal_url || '';
    
    if (!portalUrl) {
      showNotification('❌ 未找到portalUrl');
      updateStatus('未找到portalUrl');
      return;
    }
    
    console.log('[Augment Auto] Portal URL:', portalUrl);
    updateStatus('正在获取详细信息...');
    
    // 4. 调用portalUrl获取详细信息
    const portalResponse = await fetch(portalUrl, {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    });
    
    if (!portalResponse.ok) {
      console.warn('[Augment Auto] Portal API call failed, using basic data');
    }
    
    let portalData = {};
    try {
      portalData = await portalResponse.json();
      console.log('[Augment Auto] Portal data:', portalData);
    } catch (e) {
      console.warn('[Augment Auto] Failed to parse portal data');
    }
    
    // 5. 调用 /api/credits 获取准确的credits信息
    let creditsData = {};
    try {
      const creditsResponse = await fetch('https://app.augmentcode.com/api/credits', {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        credentials: 'include'
      });
      
      if (creditsResponse.ok) {
        creditsData = await creditsResponse.json();
        console.log('[Augment Auto] Credits data:', creditsData);
      }
    } catch (e) {
      console.warn('[Augment Auto] Failed to fetch credits:', e);
    }
    
    // 6. 合并三个API的数据，提取关键信息
    const email = subscriptionData.user?.email || subscriptionData.email || portalData.email || 'Unknown';
    const tenant_url = extractTenantFromApi(subscriptionData);
    
    // Credits 优先从 /api/credits 获取
    const totalCredits = creditsData.total || creditsData.totalCredits || 0;
    const usedCredits = creditsData.used || creditsData.usedCredits || 0;
    const credits = totalCredits - usedCredits;
    
    const planName = portalData.plan?.name || subscriptionData.plan?.name || subscriptionData.planName || 'Free';
    const nextBillingDate = portalData.nextBillingDate || portalData.next_billing_date || 
                            subscriptionData.nextBillingDate || subscriptionData.next_billing_date || '';
    
    // 7. 构造账号信息
    const accountInfo = {
      id: Date.now().toString(),
      email: email,
      tenant_url: tenant_url,
      session: sessionValue,
      portalUrl: portalUrl,
      credits: credits,
      planName: planName,
      nextBillingDate: nextBillingDate,
      registeredAt: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
      }).replace(/\//g, '/').replace(',', '')
    };
    
    console.log('[Augment Auto] Account info to save:', accountInfo);
    
    // 8. 保存到storage（去重）
    const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
    
    // 根据email去重
    const existingIndex = registeredAccounts.findIndex(acc => acc.email === accountInfo.email);
    
    if (existingIndex >= 0) {
      // 更新现有账号
      registeredAccounts[existingIndex] = { ...registeredAccounts[existingIndex], ...accountInfo };
      console.log('[Augment Auto] Updated existing account');
    } else {
      // 添加新账号
      registeredAccounts.push(accountInfo);
      console.log('[Augment Auto] Added new account');
    }
    
    await chrome.storage.local.set({ registeredAccounts });
    
    showNotification('✅ 用户信息提取成功！\n' + 
      `Email: ${email}\n` +
      `Tenant: ${tenant_url}\n` +
      `Credits: ${credits}`);
    
    updateStatus('用户信息已保存');
    
  } catch (error) {
    console.error('[Augment Auto] Failed to extract user info:', error);
    showNotification('❌ 提取用户信息失败\n' + error.message);
    updateStatus('提取失败');
  }
}

// {{ AURA-X: Add - 显示已注册账号弹窗. Approval: 寸止 }}
async function showRegisteredAccountsModal() {
  try {
    const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
    
    // 移除旧弹窗
    const oldModal = document.getElementById('accounts-modal');
    if (oldModal) oldModal.remove();
    
    // 创建弹窗
    const modal = document.createElement('div');
    modal.id = 'accounts-modal';
    modal.innerHTML = `
      <style>
        /* {{ AURA-X: Modify - 终极压缩，彻底避免遮挡. Approval: 寸止(终极版) }} */
        #accounts-modal {
          margin-right: 85px;
          position: fixed;
          top: 60px;
          right: 180px;
          width: 560px;
            max-height: calc(100vh - 80px);
            z-index: 9999998;
            animation: slideInFromRight 0.3s ease-out;
          }
        
        @keyframes slideInFromRight {
          from {
            transform: translateX(100%);
            opacity: 0;
          }
          to {
            transform: translateX(0);
            opacity: 1;
          }
        }
        
        .modal-content {
          background: #fff;
          border-radius: 16px;
          overflow-y: auto;
          padding: 24px;
          box-shadow: 0 10px 40px rgba(0,0,0,0.15);
          max-height: calc(100vh - 100px);
          border: 1px solid #e0e0e0;
        }
        
        .modal-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;
          padding-bottom: 16px;
          border-bottom: 2px solid #f0f0f0;
        }
        
        .modal-title {
          font-size: 20px;
          font-weight: 700;
          color: #2c3e50;
        }
        
        .modal-close {
          background: #f5f5f5;
          border: none;
          width: 32px;
          height: 32px;
          border-radius: 8px;
          cursor: pointer;
          font-size: 18px;
          transition: all 0.2s;
        }
        
        .modal-close:hover {
          background: #e0e0e0;
        }
        
        .accounts-list {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
        
        /* {{ AURA-X: Modify - 终极压缩卡片. Approval: 寸止(终极版) }} */
        .account-card-modal {
          background: #fff;
          border-radius: 8px;
          padding: 8px;
          box-shadow: 0 1px 4px rgba(0,0,0,0.08);
          color: #2c3e50;
          border: 1px solid #e0e0e0;
          transition: box-shadow 0.2s;
        }
        
        .account-card-modal:hover {
          box-shadow: 0 4px 16px rgba(0,0,0,0.15);
        }
        
        .account-header-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
        }
        
        .account-tenant {
          font-size: 13px;
          font-weight: 700;
          color: #2c3e50;
        }
        
        .account-status-badge {
          background: #e8f9f0;
          border: 1px solid #2ed573;
          padding: 2px 8px;
          border-radius: 10px;
          font-size: 10px;
          color: #2ed573;
          font-weight: 600;
        }
        
        .account-date {
          font-size: 10px;
          color: #7f8c8d;
          margin-bottom: 6px;
        }
        
        .account-email-row {
          display: flex;
          align-items: center;
          gap: 3px;
          padding: 5px 8px;
          background: #f8f9fa;
          border-radius: 5px;
          margin-bottom: 6px;
        }
        
        .account-email-row .email-icon {
          font-size: 11px;
        }
        
        .account-email-row .email-text {
          flex: 1;
          font-size: 10px;
          color: #495057;
          font-family: 'Courier New', monospace;
        }
        
        .account-email-row .copy-email-btn {
          background: transparent;
          border: none;
          cursor: pointer;
          font-size: 11px;
          padding: 2px 3px;
          border-radius: 3px;
          transition: background 0.2s;
        }
        
        .account-email-row .copy-email-btn:hover {
          background: #e9ecef;
        }
        
        .account-info-row {
          display: flex;
          gap: 6px;
          margin-bottom: 6px;
        }
        
        .info-badge {
          flex: 1;
          padding: 6px;
          border-radius: 5px;
          text-align: center;
        }
        
        .info-badge.expiry {
          background: #fff5e6;
        }
        
        .info-badge.credits {
          background: #e8f9f0;
        }
        
        .badge-label {
          font-size: 8px;
          color: #95a5a6;
          display: block;
          margin-bottom: 2px;
        }
        
        .badge-value {
          font-size: 12px;
          font-weight: 700;
        }
        
        .info-badge.expiry .badge-value {
          color: #ff9800;
        }
        
        .info-badge.credits .badge-value {
          color: #2ed573;
        }
        
        .account-actions {
          display: flex;
          gap: 3px;
          justify-content: center;
          flex-wrap: wrap;
        }
        
        .action-icon-btn-modal {
          width: 28px;
          height: 28px;
          border: none;
          border-radius: 6px;
          background: #f8f9fa;
          cursor: pointer;
          font-size: 13px;
          transition: all 0.2s;
          display: flex;
          align-items: center;
          justify-content: center;
          border: 1px solid #e9ecef;
        }
        
        .action-icon-btn-modal:hover {
          transform: scale(1.05);
          background: #e9ecef;
          box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .action-icon-btn-modal.delete-btn {
          background: #fee;
          border-color: #fcc;
        }
        
        .action-icon-btn-modal.delete-btn:hover {
          background: #fcc;
        }
        
        .empty-message {
          text-align: center;
          padding: 40px 20px;
          color: #95a5a6;
        }
      </style>
      <div class="modal-content">
        <div class="modal-header">
          <div class="modal-title">✅ 已注册账号</div>
          <button class="modal-close" onclick="this.closest('#accounts-modal').remove()">✕</button>
        </div>
        <div class="accounts-list">
          ${registeredAccounts.length === 0 ? 
            '<div class="empty-message">暂无已注册账号</div>' :
            registeredAccounts.map(acc => {
              // 格式化邮箱
              const email = acc.email || 'Unknown';
              const emailParts = email.split('@');
              let maskedEmail = email;
              if (emailParts.length === 2) {
                const localPart = emailParts[0];
                const domain = emailParts[1];
                if (localPart.length > 6) {
                  maskedEmail = localPart.substring(0, 3) + '****' + localPart.substring(localPart.length - 2) + '@' + domain;
                } else if (localPart.length > 2) {
                  maskedEmail = localPart.substring(0, 2) + '****' + '@' + domain;
                }
              }
              
              // 格式化tenant
              let tenantDisplay = acc.tenant_url || 'Unknown';
              if (tenantDisplay !== 'Unknown' && tenantDisplay.includes('://')) {
                tenantDisplay = tenantDisplay.replace('https://', '').replace('http://', '').replace('/', '');
              }
              
              // 格式化过期时间
              let expiryDisplay = '未知';
              if (acc.nextBillingDate) {
                try {
                  const date = new Date(acc.nextBillingDate);
                  expiryDisplay = (date.getMonth() + 1) + '/' + date.getDate() + ' ' + 
                                 String(date.getHours()).padStart(2, '0') + ':' + 
                                 String(date.getMinutes()).padStart(2, '0');
                } catch (e) {
                  expiryDisplay = acc.nextBillingDate;
                }
              }
              
              return `
              <div class="account-card-modal">
                <div class="account-header-row">
                  <div class="account-tenant">${tenantDisplay}</div>
                  <div class="account-status-badge">✅ 正常</div>
                </div>
                <div class="account-date">${acc.registeredAt || '未知'}</div>
                <div class="account-email-row">
                  <span class="email-icon">📧</span>
                  <span class="email-text">${maskedEmail}</span>
                  <button class="copy-email-btn" onclick="event.stopPropagation(); navigator.clipboard.writeText('${email}').then(() => alert('邮箱已复制'));" title="复制完整邮箱">📋</button>
                </div>
                <div class="account-info-row">
                  <div class="info-badge expiry">
                    <span class="badge-label">过期：</span>
                    <span class="badge-value">${expiryDisplay}</span>
                  </div>
                  <div class="info-badge credits">
                    <span class="badge-label">剩余：</span>
                    <span class="badge-value">${acc.credits || 0}</span>
                  </div>
                </div>
                <div class="account-actions">
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); navigator.clipboard.writeText('${acc.session || acc.token || ''}').then(() => alert('Session已复制'));" title="复制Session">🔑</button>
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); navigator.clipboard.writeText('${acc.token || acc.session || ''}').then(() => alert('Token已复制'));" title="复制Token">📋</button>
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); navigator.clipboard.writeText(JSON.stringify({email:'${acc.email}',session:'${acc.session}',token:'${acc.token}',tenant:'${acc.tenant_url}',credits:${acc.credits || 0}}, null, 2)).then(() => alert('完整信息已复制'));" title="复制完整信息">📄</button>
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); if('${acc.portalUrl}') window.open('${acc.portalUrl}', '_blank'); else alert('无Portal URL');" title="打开Portal">🔗</button>
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); alert('刷新功能开发中');" title="刷新信息">🔄</button>
                  <button class="action-icon-btn-modal" onclick="event.stopPropagation(); alert('编辑功能开发中');" title="编辑">✏️</button>
                  <button class="action-icon-btn-modal delete-btn" onclick="event.stopPropagation(); if(confirm('确定删除账号？')){alert('删除功能待实现');}" title="删除">🗑️</button>
                </div>
              </div>
            `;
            }).join('')
          }
        </div>
      </div>
    `;
    
    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove();
      }
    });
    
    document.body.appendChild(modal);
    
  } catch (error) {
    console.error('[Augment Auto] Failed to show accounts modal:', error);
    showNotification('❌ 加载账号失败');
  }
}

function showNotification(message) {
  const oldNotif = document.querySelector('.augment-auto-notification');
  if (oldNotif) oldNotif.remove();
  
  const notification = document.createElement('div');
  notification.className = 'augment-auto-notification';
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 16px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.2);
    z-index: 999998;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 14px;
    max-width: 400px;
    white-space: pre-line;
    animation: slideDown 0.3s ease-out;
  `;
  
  notification.textContent = message;
  document.body.appendChild(notification);
  
  const style = document.createElement('style');
  style.textContent = `
    @keyframes slideDown {
      from { transform: translateX(-50%) translateY(-100px); opacity: 0; }
      to { transform: translateX(-50%) translateY(0); opacity: 1; }
    }
  `;
  document.head.appendChild(style);
  
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateX(-50%) translateY(-100px)';
    setTimeout(() => notification.remove(), 300);
  }, 3000);
}

// {{ AURA-X: Add - onboard和complete-signup页面处理. Approval: 寸止 }}

// {{ AURA-X: Delete - 删除冗余的 onboard 和 complete-signup 页面处理. Approval: 寸止 }}
// 这些函数已被删除，使用简化的两步流程：
// 步骤1: auth/continue → 提取并暂存 (extractAndSaveAccountInfo)
// 步骤2: subscription → 获取完整信息并保存 (fetchSubscriptionInfo)

// 页面加载时自动初始化
console.log('[Augment Auto] Script initializing...', document.readyState);

// {{ AURA-X: Modify - 立即创建面板，不等待. Approval: 寸止 }}
async function tryInit() {
  console.log('[Augment Auto] Trying to init...');

  // 立即创建面板，不等待
  createSidePanel();

  // 等待面板DOM渲染完成
  await new Promise(resolve => setTimeout(resolve, 100));

  // 延迟500ms后初始化自动化
  await new Promise(resolve => setTimeout(resolve, 500));

  // 再初始化自动化
  initAutomation();
}

// {{ AURA-X: Add - 定期检查并确保面板始终存在. Approval: 寸止 }}
function ensurePanelExists() {
  const panel = document.getElementById('augment-auto-panel');
  const buttonsContainer = document.getElementById('panel-buttons');

  if (!panel || !buttonsContainer) {
    console.log('[Augment Auto] Panel or buttons missing, recreating...');
    createSidePanel();
    // 如果面板不存在，说明可能是新页面或页面重新加载，重新初始化按钮
    setTimeout(() => {
      handleAuthPage(null);
    }, 100);
  }
}

// 每1秒检查一次面板是否存在（更激进）
setInterval(ensurePanelExists, 1000);

// {{ AURA-X: Add - 监听页面变化，确保按钮始终可用. Approval: 寸止 }}
// 监听body变化，如果页面内容变化（比如错误提示出现），重新加载按钮
const observer = new MutationObserver(() => {
  // 检查是否有验证失败的错误提示
  const verificationError = document.querySelector('.text-red-100');
  if (verificationError && verificationError.textContent.includes('Verification failed')) {
    console.log('[Augment Auto] Verification failed detected via MutationObserver, ensuring buttons...');
    ensurePanelExists();
  }
});

// 配置观察器选项
const observerConfig = {
  childList: true,
  subtree: true,
  attributes: true,
  attributeFilter: ['class', 'style']
};

// 开始观察body
if (document.body) {
  observer.observe(document.body, observerConfig);
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', tryInit);
} else {
  tryInit();
}
